﻿using MCUPackage;
using MCUPackage.Utils;
using System;
using System.ComponentModel;

namespace SxPackages.STC32G.Models
{
	[Serializable]
	class USARTSPIOptions : SPIOptions
	{
		public override Boolean Enable
		{
			get => base.Enable;
			set
			{
				if (value != base.Enable)
				{
					if (value)
					{
						if (this.Type == SPITypes.USART1)
						{
							if (mParent.Uarts != null && mParent.mUarts.USART1.Enable)
							{
								GuiUtils.MsgBox("串口1已经被启用, 无法作为SPI口使用!");
								return;
							}
							if (this.Pins == SPIPins.SS_P35_MOSI_P34_MISO_P33_SCLK_P32 
								|| this.Pins == SPIPins.SS_P74_MOSI_P75_MISO_P76_SCLK_P77)
							{
								GuiUtils.MsgBox("串口1SPI无法设置该组引脚!");
								return;
							}
						}
						if (this.Type == SPITypes.USART2)
						{
							if (mParent.Uarts != null && mParent.mUarts.USART2.Enable)
							{
								GuiUtils.MsgBox("串口2已经被占用, 无法作为SPI口使用!");
								return;
							}
							if (this.Pins == SPIPins.SS_P35_MOSI_P34_MISO_P33_SCLK_P32
								|| this.Pins == SPIPins.SS_P64_MOSI_P65_MISO_P66_SCLK_P67)
							{
								GuiUtils.MsgBox("串口2SPI无法设置该组引脚!");
								return;
							}
						}
					}
					base.Enable = value;
				}
			}
		}

		[Browsable(false)]
		public override Boolean SSIG => true;

		[Browsable(false)]
		public override Boolean EnableDMA => false;
		[Browsable(false)]
		public override Boolean EnableRcv => false;
		[Browsable(false)]
		public override Boolean EnableSnd => false;
		[Browsable(false)]
		public override Int32 Length { get => base.Length; set => base.Length = value; }
		[Browsable(false)]
		public override Boolean EnableSS => false;
		[Browsable(false)]
		public override PriorityTypes DMAPriority { get => base.DMAPriority; set => base.DMAPriority = value; }
		[Browsable(false)]
		public override PriorityTypes BusPriority { get => base.BusPriority; set => base.BusPriority = value; }

		protected override void SetPins(String[] aPins)
		{
			base.SetPins(aPins);

			var purpose = this.Type == SPITypes.USART1 ? PinPurpose.USART1_SPI_SS : PinPurpose.USART2_SPI_SS;
			for (int i = 0; i < 4; i++)
			{
				mParent.SetPinPurpose(aPins[i], purpose, false);
				purpose++;
			}
		}

		public USARTSPIOptions(SPITypes aType, STC32GQFP64 aParent) : base(aParent)
		{
			if (aType == SPITypes.USART1 || aType == SPITypes.USART2)
			{
				this.Type = aType;
			}
			else
			{
				throw new Exception("无效的SPI类型!");
			}
		}
	}
}
